package com.xoa.service.smsDelivery.impl;


import com.xoa.dao.sms2.Sms2Mapper;

import com.xoa.dao.smsSettings.SmsSettingsMapper;
import com.xoa.model.sms2.Sms2;


import com.xoa.model.smsSettings.SmsSettings;
import com.xoa.service.smsDelivery.Sms2Service;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.page.PageParams;
import com.xoa.util.sendUtil.send;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.*;

import java.net.HttpURLConnection;
import java.net.URL;

@Service
public class Sms2ServiceImpl implements Sms2Service {

    @Resource
    private Sms2Mapper sms2Mapper;
    @Resource
    private SmsSettingsMapper smsSettingsMapper;


    @Override
    public ToJson<Sms2> selectSms2(HttpServletRequest request, HttpServletResponse response, Integer page, Integer pageSize, boolean useFlag, Sms2 sms2) {

        ToJson<Sms2> json = new ToJson<Sms2>();
        PageParams pageParams = new PageParams();
        pageParams.setPageSize(pageSize);
        pageParams.setPage(page);
        pageParams.setUseFlag(useFlag);

        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("page", pageParams);
            map.put("sms2",sms2);
            List<Sms2> list = sms2Mapper.selectSms2(map);
          /*  SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(pzFullRelease.getpOutPrisonTime());
            pzFullRelease.setOutTime(format);

            String format1 = sdf.format(pzFullRelease.getpJoinDate());
            pzFullRelease.setJoinDate(format1);*/

           /* Integer smsCountByMap = sms2Mapper.getSmsCountByMap(map);*/

            if (list.size() > 0) {
                json.setObj(list);
                json.setTotleNum(pageParams.getTotal());
                json.setMsg("success");
                json.setFlag(0);
            }
        } catch (Exception e) {

            json.setFlag(1);
            json.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return json;

    }

    @Transactional
    public ToJson selectSms2ById(HttpServletRequest request, Integer smsId) {
        ToJson<Sms2> json = new ToJson<Sms2>();
        try {
            Sms2 sms2 = sms2Mapper.selectByPrimaryKey(smsId);
          /*  SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(pzFullRelease.getpOutPrisonTime());
            pzFullRelease.setOutTime(format);

            String format1 = sdf.format(pzFullRelease.getpJoinDate());
            pzFullRelease.setJoinDate(format1);*/

            json.setObject(sms2);
            json.setFlag(0);
            json.setMsg("ok");
        } catch (Exception e) {

            json.setFlag(1);
            json.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return json;
    }

    @Transactional
    public ToJson insertSms2(Sms2 sms2) {
        ToJson<Sms2> toJson = new ToJson<Sms2>(1, "error");
        try {
            int temp = sms2Mapper.insertSelective(sms2);
            if (temp > 0) {
                toJson.setFlag(0);
                toJson.setMsg("success");
            }
        } catch (Exception e) {
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
            e.printStackTrace();
        }

        return toJson;

    }

    @Transactional
    public ToJson delSms2(Sms2 sms2) {
        ToJson toJson = new ToJson(1, "error");
        try {
            int temp = sms2Mapper.delSms2(sms2);
            if (temp > 0) {
                toJson.setFlag(0);
                toJson.setMsg("success");
            }
        } catch (Exception e) {
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return toJson;
    }
    @Transactional
    public ToJson upSms2(Sms2 sms2) {
        ToJson toJson = new ToJson<>(1, "error");
        try {
            int temp = sms2Mapper.updateByPrimaryKeySelective(sms2);
            if (temp > 0) {
                toJson.setFlag(0);
                toJson.setMsg("success");
            }
        } catch (Exception e) {
            toJson.setFlag(1);
            toJson.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return toJson;

    }

    @Override
    public ToJson SendSms() {
        return null;
    }

    /**
    * @author 程叶同
    * @date 2018/7/31 18:58
    * @desc  excel导入短信发送
    */
    @Override
    public BaseWrapper sendMessageByExcel(MultipartFile file){
        BaseWrapper baseWrapper=new BaseWrapper();
        //读取当前配置
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
              StringBuffer buffer=new StringBuffer();
        if(osName.toLowerCase().startsWith("win")){
            //sb=sb.append(rb.getString("upload.win"));
            //判断路径是否是相对路径，如果是的话，加上运行的路径
            String uploadPath = rb.getString("upload.win");
            if(uploadPath.indexOf(":")==-1){
                //获取运行时的路径
                String basePath = this.getClass().getClassLoader().getResource(".").getPath()+ File.pathSeparator;
                //获取截取后的路径
                String str2 = "";
                if(basePath.indexOf("/xoa")!=-1){
                    //获取字符串的长度
                    int length = basePath.length();
                    //返回指定字符在此字符串中第一次出现处的索引
                    int index = basePath.indexOf("/xoa");
                    //从指定位置开始到指定位置结束截取字符串
                    str2=basePath.substring(0,index);
                }
                path = path.append(str2 + "/xoa");
            }
            path.append(uploadPath);
            buffer=buffer.append(rb.getString("upload.win"));
        }else{
            path=path.append(rb.getString("upload.linux"));
            buffer=buffer.append(rb.getString("upload.linux"));
        }
            // 判断是否为空文件
            if (file.isEmpty()) {
            baseWrapper.setMsg("请上传文件！");
            baseWrapper.setFlag(true);
            return baseWrapper;
            } else {
                File file1 = new File(path.toString());
                if (!file1.exists()) {
                    file1.mkdirs();
                }
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                    String readPath = path.append(System.getProperty("file.separator")).append(newFileName).toString();

                    try (InputStream is = new FileInputStream(readPath);){
                    file.transferTo(dest);
                    HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
                    // 循环工作表Sheet
                    StringBuffer contextString=new StringBuffer();
                    StringBuffer mobileString=new StringBuffer();
                    Map<String,Object> map=new HashMap<>();
                    List<SmsSettings> list = smsSettingsMapper.selectSmsSettings(map);
                    for(SmsSettings smsSettings:list){
                        smsSettings.setSign("sign="+smsSettings.getSign());
                    }
                    String result="";
                    int successCount=0;
                    for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
                        HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
                        if (hssfSheet == null) {
                            continue;
                        }
                        // 循环行Row
                        for (int rowNum = 3; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                            HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                            if (hssfRow != null) {
                                HSSFCell mobiemodel = hssfRow.getCell(0);
                                HSSFCell contentmodel = hssfRow.getCell(1);
                                if (mobiemodel != null && contentmodel != null) {
                                    String mobie=mobiemodel.getStringCellValue();
                                    String content=contentmodel.getStringCellValue();
                                    mobileString.append(mobie);
                                    contextString.append(content);
                                    if (!StringUtils.checkNull(mobileString.toString())&&!StringUtils.checkNull(contextString.toString())) {
                                        //发送短信
                                        for(SmsSettings smsSettings:list){
                                            if(smsSettings.getState().equals("1")){
                                                StringBuffer extno  = new StringBuffer(smsSettings.getExtend2());
                                                result = send.doPost(mobileString, contextString, smsSettings.getProtocol(), smsSettings.getHost(), smsSettings.getPort(),
                                                        smsSettings.getUsername(), smsSettings.getPwd(), smsSettings.getContentField(),
                                                        smsSettings.getCode(), smsSettings.getMobile(), smsSettings.getTimeContent(), smsSettings.getSign(), smsSettings.getLocation(),
                                                        smsSettings.getExtend1(), smsSettings.getExtend2(), smsSettings.getExtend3(), smsSettings.getExtend4(), "1",
                                                        "");
                                            }
                                        }
                                        if(result!=null&&!"".equals(result)){
                                            String[] split = result.split(",");
                                            if ("0".equals(split[0])) {
                                                successCount=successCount+Integer.parseInt(split[3]);
                                            }
                                        }
                                    }
                                }
                            }
                        }

                    }
                    //导入结束 删除文件
                    dest.delete();
                    baseWrapper.setMsg("成功发送:"+successCount+"条");
                    baseWrapper.setFlag(true);
                    baseWrapper.setStatus(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

        }
        return  baseWrapper;
    }

}
